import { useVbenDrawer, useVbenModal } from '@vben/common-ui'
import { useMessage } from './useMessage'
import { $t } from '@vben/locales'
import { message } from 'ant-design-vue'

/**
 * 用于处理增删改查 一般用于页面上
 */
export function usePageCURD<ListItem extends Record<string, any>>(opts: {
    beforeDelParams?: (...args: any[]) => any | Promise<any>
    delApi?: (...args: any[]) => Promise<any>
    getSelectRows?: () => ListItem[]
    idKey?: string
    modalOptions?: Parameters<typeof useVbenDrawer>[0] & Parameters<typeof useVbenModal>[0]
    modalType?: 'drawer' | 'modal'
    onSuccess?: (...args: any[]) => any
    statusKey?: string
    updateStatusApi?: (...args: any[]) => Promise<any>
    updateStatusSuccess?: (...args: any[]) => Promise<any>
}) {
    const {
        delApi,
        idKey = 'id',
        statusKey = 'status',
        updateStatusApi,
        modalOptions,
        updateStatusSuccess,
        onSuccess,
        getSelectRows,
        modalType = 'modal'
    } = opts

    const useOpts = opts

    const [FormModal, formModalApi] =
        modalType === 'modal' ? useVbenModal(modalOptions) : useVbenDrawer(modalOptions)

    // 打开模态框
    function openModal(data: Record<string, any> = {}) {
        // 设置模态框数据
        formModalApi.setData(data)
        formModalApi.open()
    }

    function add(params?: Record<string, any>) {
        openModal({ ...params })
    }

    function edit(record: ListItem, params?: Record<string, any>) {
        openModal({
            record,
            ...params
        })
    }

    function viewDetail(record: ListItem, params?: Record<string, any>) {
        openModal({
            isViewMode: true,
            record,
            ...params
        })
    }

    /**
     * 更新状态
     * @param status
     * @param record
     */
    async function updateStatus(status: number, record: ListItem) {
        if (updateStatusApi) {
            await updateStatusApi({
                [statusKey]: status,
                id: record[idKey]
            })
        }

        await updateStatusSuccess?.(record, status)
    }
    /**
     * 删除记录
     * @param record
     */
    async function del(
        record: ListItem,
        opts?: { isShowToast?: boolean; isSuccessCallback?: boolean }
    ) {
        if (delApi) {
            let params = [record[idKey]]
            if (typeof useOpts?.beforeDelParams === 'function') {
                params = await useOpts.beforeDelParams(record, idKey)
            }

            await delApi(params, record)
        }

        const { isSuccessCallback = true, isShowToast = true } = opts || {}

        if (isShowToast) {
            message.success($t('common.deleteSuccess'))
        }

        if (isSuccessCallback) {
            handleSuccess()
        }
    }

    function delBatch() {
        if (!getSelectRows) return
        const rows = getSelectRows()

        const ids = rows.map((item: any) => item[idKey])

        if (ids.length === 0) {
            message.error($t('common.comfirmDeleteData'))
            return
        }

        const { createConfirm } = useMessage()
        createConfirm({
            title: $t('common.tip'),
            iconType: 'warning',
            content: $t('common.confirmDelete'),
            onOk: async () => {
                if (delApi) {
                    await delApi(ids)
                    handleSuccess()
                }
            }
        })
    }

    function handleSuccess() {
        onSuccess?.()
    }

    return {
        FormModal,
        formModalApi,
        add,
        edit,
        viewDetail,
        updateStatus,
        del,
        delBatch,
        openModal
    }
}
